<?php

namespace app\controller\api\controller;

use app\popo\model\Dish;
use app\service\DishService;
use app\support\ResponseHelper;
use DI\Attribute\Inject;
use Shayvmo\WebmanAnnotations\Annotations\DeleteMapping;
use Shayvmo\WebmanAnnotations\Annotations\GetMapping;
use Shayvmo\WebmanAnnotations\Annotations\PostMapping;
use Shayvmo\WebmanAnnotations\Annotations\PutMapping;
use Shayvmo\WebmanAnnotations\Annotations\RestController;
use support\Log;
use support\Response;
use Webman\Http\Request;

#[RestController("/api/dish")]
class DishController
{
    #[Inject]
    protected DishService $dishService;

    #[GetMapping("/page")]
    public function listOf(Request $request): Response
    {
       $listContainer = $this->dishService->listOf($request->all());
       return ResponseHelper::successJson($listContainer->toArray());
    }

    #[GetMapping('{id}')]
    public function getDishById($id): Response
    {
        return ResponseHelper::successJson($this->dishService->getDishById($id));
    }

    #[PostMapping]
    public function saveWithFlavors(Request $request): Response
    {
        try {
            $data = \support\Db::transaction(function () use ($request) {
                return $this->dishService->saveWithFlavors($request->all());
            });

            return ResponseHelper::successJson($data);
        } catch (\Throwable $throwable) {
            return ResponseHelper::failJson($throwable->getMessage());
        }
    }

    #[DeleteMapping]
    public function delete(Request $request): Response
    {
        try {
            \support\Db::beginTransaction();
            $this->dishService->deleteDishsWithFlavors($request->all());
            \support\Db::commit();
            return ResponseHelper::successJson();
        } catch (\Throwable $throwable) {
            \support\Db::rollBack();
            return ResponseHelper::failJson($throwable->getMessage());
        }
    }

    #[PostMapping("/status/{status}")]
    public function startOrStop($status, Request $request): Response
    {
        $this->dishService->startOrStop($status, $request->get("id"));
        return ResponseHelper::successJson();
    }

    #[PutMapping]
    public function update(Request $request): Response
    {
        try {
            \support\Db::transaction(function () use ($request) {
                $this->dishService->update($request->all());
            });

            return ResponseHelper::successJson();
        } catch (\Throwable $throwable) {
            return ResponseHelper::failJson($throwable->getMessage());
        }
    }

    #[GetMapping("/list")]
    public function list(Request $request)
    {
        $data = $this->dishService->list($request->all());

        return ResponseHelper::successJson($data);
    }
}